var express = require("express")
var router = express.Router()
const { getAll, getById, exec } = require("../db/index")

router.get("/", async (req, res) => {
  // 操作数据库
  let sql = `select * from notice order by id desc`
  const data = await getAll(sql)
  res.send({
    code: 0,
    message: "获取所有公告成功",
    result: {
      data: data,
    },
  })
})
router.post("/", async (req, res) => {
  const { tittle, content } = req.body
  let sql = `insert into notice (tittle,content,time) values ('${tittle}','${content}',now())`
  const data = await exec(sql)
  res.send({
    code: 0,
    message: "发布公告成功",
    data: data,
  })
})
router.put("/:id", async (req, res) => {
  const id = req.params.id
  const { tittle, content } = req.body
  let sql = `update notice set tittle='${tittle}',content='${content}' where id = ${id}`
  const data = await exec(sql)
  res.send({
    code: 0,
    message: "修改公告成功",
    data: data,
  })
})
router.delete("/:id", async (req, res) => {
  const id = req.params.id
  let sql = `delete from notice where id ='${id}' `
  const data = await exec(sql)
  res.send({
    code: 0,
    message: "删除公告成功",
    data: data,
  })
})
module.exports = router
